package com.shenfa.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.gmc.util.config.NetReader;
import net.gmc.util.netserver.NetServerUtil;
import net.gmc.util.netserver.command.CommandMaker;
import net.gmc.util.netserver.control.NetServerFlowControl;
import net.gmc.util.netserver.flow.NetServerFlowInterface;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.shenfa.bean.Fodder;
import com.shenfa.bean.Paper;
import com.shenfa.bean.PaperInfo;
import com.shenfa.bean.RuleOper;
import com.shenfa.bean.RuleParam;
import com.shenfa.bean.Template;
import com.shenfa.bean.TemplateArea;
import com.shenfa.bean.Template_Sub;
import com.shenfa.bean.bill.rule.RuleMaster;
import com.shenfa.dao.FodderDao;
import com.shenfa.dao.PaperDao;
import com.shenfa.dao.RuleDao;
import com.shenfa.dao.TemplateAreaDao;
import com.shenfa.dao.TemplateDao;
import com.shenfa.tools.SteelDataApp;
import com.shenfa.util.Config;
import com.shenfa.util.ReadShowFile;
import com.shenfa.util.sequence.SequenceUtil;

/**
 * 个性化区域规则
 * 
 * @author yanglong
 *
 */
public class RuleService {

	@Autowired
	private RuleDao ruleDao;
	
	@Autowired
	private TemplateDao templateDao;

	@Autowired
	private SequenceUtil sequenceUtil;
	
	@Autowired
	private FodderDao fodderDao;
	
	@Autowired
	private PaperDao paperDao;
	
	@Autowired
	private TemplateAreaDao tempAreadao;
	
	private static Logger log = Logger.getLogger(RuleService.class);

	
	public List<RuleParam> listRuleByArea(String areaNo){
		return ruleDao.listRuleByArea(areaNo);
	}
	
	/**
	 * 查询所有个性化区域规则列表
	 * 
	 * @author yanglong
	 */
	public List<RuleMaster> doGridList(RuleMaster ruleMaster, int skipResults,
			int maxResults) {
		return ruleDao.queryGridList(ruleMaster, skipResults, maxResults);
	}
	public int queryCountRm(RuleMaster ruleMaster) {
		return ruleDao.queryCountRm(ruleMaster);
	}
	
	/**
	 * 查询审核规则列表
	 * 
	 * @author yanglong
	 */
	public List<RuleMaster> doGridListSh(RuleMaster ruleMaster, int skipResults,
			int maxResults) {
		return ruleDao.queryGridListSh(ruleMaster, skipResults, maxResults);
	}
	public int queryCountRmSh(RuleMaster ruleMaster) {
		return ruleDao.queryCountRmSh(ruleMaster);
	}
	
	/**
	 * 查询规则详细信息
	 * @param ruleMaster
	 * @return
	 */
	public List<RuleMaster> listRuleAll(RuleMaster ruleMaster) {
		List<Template> templist=templateDao.showList(ruleMaster.getCard_id(),0,100);
		//遍历模板查询相应规则
		for(Template temp:templist){
			
			
		}
		return null;
	}
	public int getCountRmAll(RuleMaster ruleMaster) {
		List<Template> templist=templateDao.showList(ruleMaster.getCard_id(),0,100);
		//遍历模板查询相应规则
		for(Template temp:templist){
			
			
		}
		return 0;
	}
	
	
	/**
	 * 添加个性化区域规则信息
	 * 
	 * @author yanglong
	 * 
	 * @return	true成功，false失败
	 */
	public boolean addRule(RuleMaster rulemaster) {
		//rulemaster.setRule_no(sequenceUtil.getSequence(SequenceUtil.SEQ_RULE_M));
		rulemaster.setCreate_time(this.formatRule(rulemaster.getCreate_time(), '1'));
		return ruleDao.addRule(rulemaster);
	}

	/**
	 * 删除个性化区域规则
	 * 
	 * @author yanglong
	 * 
	 * @return	true成功，false失败
	 */
	public boolean deleteRule(RuleMaster rulemaster) {
		return ruleDao.deleteRule(rulemaster);
	}
	
	/**
	 * 修改个性化区域规则
	 * 
	 * @author yanglong
	 * 
	 * @return	true成功，false失败
	 */
	public boolean updateRule(RuleMaster ruleMaster) {
		return ruleDao.updateRule(ruleMaster);
	}

	/**
	 * 格式化月
	 * 
	 * @param date [需要格式花的字符串]
	 * @param flag [格式化标识]
	 * @return
	 */
	public String formatRule(String date, char flag) {
		SteelDataApp app = new SteelDataApp(date);
		if (flag == '1') {
			date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(app.getDate());
		} else {
			date = new SimpleDateFormat("yyyy-MM").format(app.getDate());
		}
		return date;
	}
	/**
	 * 添加规则从表信息
	 * 
	 * @author yanghaoyu
	 * 
	 * @return	true成功，false失败
	 */
	public boolean addRuleParam(RuleParam ruleParam) {
		//页面直接获取id和ruleno 所以直接保存
		//ruleParam.setId(sequenceUtil.getSequence(SequenceUtil.SEQ_OTHER_INTEGER));
		//ruleParam.setRuleno(rulemaster.getRule_no());
		return ruleDao.addRuleParam(ruleParam);
	}
	/**
	 * 删除规则从表信息 删除条件是单击一行信息进行删除
	 * 
	 * @author yanghaoyu
	 * 
	 * @return	true成功，false失败
	 */
	public boolean deleteRuleParambyId(RuleParam ruleParam) {
		return ruleDao.deleteRuleParambyid(ruleParam);
	}

	/**
	 *修改规则从表信息 
	 * 
	 * @author yanghaoyu
	 * 
	 * @return	true成功，false失败
	 */
	public boolean updateRuleParambyId(RuleParam ruleParam) {
		return ruleDao.updateRuleParam(ruleParam);
	}

	/**
	 * 查询规则从表列表
	 * 
	 * @author yanghaoyu
	 */
	public List<RuleParam> listRuleParam(RuleMaster rulemaster) {
		return ruleDao.listRuleParamByruluNo(rulemaster);
	}
	/**
	 * 查询规则从从表列表
	 * 
	 * @author yanghaoyu
	 */
	public List<RuleOper> listRuleOper(RuleParam ruleParam) {
		return ruleDao.listRuleOperByid(ruleParam);
	}
	/**
	 * 添加规则从从表信息
	 * 
	 * @author yanghaoyu
	 * 
	 * @return	true成功，false失败
	 */
	public boolean addRuleOper(RuleOper ruleOper) {
		return ruleDao.addRuleOper(ruleOper);
	}
	/**
	 * 删除规则从从表信息 单行选择
	 * 
	 * @author yanghaoyu
	 * 
	 * @return	true成功，false失败
	 */
	public boolean delRuleOper(RuleOper ruleOper) {
		
		return ruleDao.deleteRuleOperbyid(ruleOper);
	}
	/**
	 *修改规则从从表信息 
	 * 
	 * @author yanghaoyu
	 * 
	 * @return	true成功，false失败
	 */
	public boolean updateRuleOper(RuleOper ruleOper) {
		return ruleDao.updateRuleOper(ruleOper);
	}

	/**
	 * 获取个性化区域规则表的序列号
	 */
	public String getRuleNo() {
		return sequenceUtil.getSequence(SequenceUtil.SEQ_RULE_M);
	}
	/**
	 * 获取个性化区域规则从表的序列号和丛丛的IDX
	 */
	public int getRuleNoOrIdx() {
		String aas=sequenceUtil.getSequence(SequenceUtil.SEQ_OTHER_INTEGER).toString();
		int a=Integer.parseInt(aas);
		return a;
	}
	//循环添加RuleParam集合，并且，出错时候跳出循环
	public boolean updateListRuleParam(List<RuleParam> ruleParams)
	{
		boolean b=true;
		
		 for (RuleParam ruleParam : ruleParams) {
			 List<RuleParam> ruleData= ruleDao.listRuleParamByID(ruleParam);
			 if(ruleData.size()>0){
				 b=ruleDao.updateRuleParam(ruleParam);
			 }else{
				 b=ruleDao.addRuleParam(ruleParam);
			 }
			if(b==false)
				break;
		}
         return b;
	}
	//循环添加RuleOper集合，并且，出错时候跳出循环
	public boolean updateListRuleOper(List<RuleOper> ruleOpers)
	{
		boolean b=true;
         for (RuleOper ruleOper : ruleOpers) {
			 b=ruleDao.addRuleOper(ruleOper);
			if(!b)break;
		}
         return b;
	}
	
	public String rulePDF(RuleParam rule){
		ArrayList<HashMap<String, Object>> dataList = new ArrayList<HashMap<String,Object>>();
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		HashMap<String, Object> xmlDataMap = new HashMap<String, Object>();
		
		//rule.getRuleno() 是模板的id,通过此条件得到模板
		Template temp=new Template();
		if(null==rule.getRuleno()){
			log.debug("个性化区域规则浏览：模板ID为空！");
			return "模板ID为空！!";
		}
		temp.setId(rule.getRuleno());
		List<Template> tempList=templateDao.getTmpParamsList(temp);
		
		if(tempList==null || tempList.size()<1){
			log.debug("个性化区域规则浏览：通过模板ID没有到获取模板！模板ID为："+rule.getRuleno());
			return "模板没有找到！";
		}else{
			temp=tempList.get(0);
		}
		
		//得到素材
		Fodder fodder=new Fodder();
		if(null==rule.getFodder()){
			log.debug("个性化区域规则浏览：没有素材ID！");
			return "没有素材ID！";
		}
		fodder.setId(rule.getFodder());
		List<Fodder> fodderList=fodderDao.queryList(fodder, 0, 10);
		if(fodderList==null  || fodderList.size()<1){
			log.debug("个性化区域规则浏览：根据素材ID没有找到素材数据！素材ID为："+rule.getFodder());
			return "素材没找到！";
		}else{
			fodder=fodderList.get(0);
		}
		
		String areano="";
		String paperid="";
		if(rule.getId().indexOf("|")!=-1){
			areano=rule.getId().substring(0, rule.getId().indexOf("|"));
			paperid=rule.getId().substring(rule.getId().indexOf("|")+1, rule.getId().length());
		}else{
			areano=rule.getId();
		}
		String areaType=rule.getFodderName();//假数据，区域素材类型
		String ruleno=rule.getFodderType();//假数据，区域编号
		
		try {
			
			//设置区域数据
			Template_Sub temSub=new Template_Sub();
			temSub.setStencil_no(temp.getId());
			List<Template_Sub> subList=templateDao.getTemplateSubs(temSub);
			if(subList.size()<1){
				log.debug("个性化区域规则浏览：根据模板ID没找到设置的区域数据！");
				return "没有找到该模板的默认区域规则数据！";
			}
			log.debug("个性化区域规则浏览：设置的区域数据大小："+subList.size());
			int k=1;
			for (int i = 0; i < subList.size(); i++) {
				Template_Sub subTemp = subList.get(i);
				xmlDataMap.put("dif"+k, subTemp.getIn_name());
				k=k+2;
			}
			
			
			//通过模板id获得模板个性化区域信息
			TemplateArea temparea=new TemplateArea();
			temparea.setTempno(temp.getId());
			List<TemplateArea> list=tempAreadao.queryTempArea(temparea);
			log.debug("个性化区域规则浏览：模板个性化区域信息大小："+list.size());
			
			//通过 区域 获取他所在的默认 个性 化规则
			TemplateArea templateArea;
			RuleMaster rulem=new RuleMaster();
			List<RuleParam> rupList=new ArrayList<RuleParam>();
			rulem.setRule_type("0");
			List<RuleMaster> ruleList=new ArrayList<RuleMaster>();
			List<RuleMaster> mList=null;
			for (int i = 0; i < list.size(); i++) {
				templateArea=list.get(i);
				rulem.setStencil_no(temp.getId());
				rulem.setAreaNo(String.valueOf(templateArea.getId()));
				mList=ruleDao.queryGridList(rulem);
				if(mList==null || mList.size()<1){
					return "默认规则不全，请配置全！";
				}else{
					for (int j = 0; j < mList.size(); j++) {
						rupList=ruleDao.listRuleParamByruluNo(mList.get(j));
						if(ruleList.size()<(i+1)){
							if(rupList.size()>0){
								ruleList.add(mList.get(j));
							}
						}
					}
					if(ruleList.size()!=(i+1)){
						return "默认规则不全，请配置全！";
					}
				}
			}
			
			if(list.size()!=ruleList.size()){
				return "默认规则不全，请配置全！";
			}
			
			
			
			log.debug("个性化区域规则浏览：个性化区域规则信息大小："+ruleList.size());
			//如果是纸质账单
			if(temp.getType().equals("1")){
				//构造当前区域xml
				
				//读区域类型，如果是3列表类型或者4自适应类型则查询所有该区域的规则并拼装xml
				/*
				 * for(){
				 * 
				 * */
				String  xml="";
				String docname=fodder.getDocname()==null?"":fodder.getDocname();
				String url=fodder.getUrl()==null?"":fodder.getUrl();
				
				if(areaType.equals("3") || areaType.equals("4")){
					//查询当前区域下的规则列表
					RuleMaster ru=new RuleMaster();
					ru.setAreaNo(ruleno);
					List<RuleParam> rparamList=ruleDao.listRuleParamByruluNo(ru);
					Fodder f=new Fodder();
					List<Fodder> listFodder=new ArrayList<Fodder>();
					for (RuleParam rp : rparamList) {
						f.setId(rp.getFodder());
						f.setId(rp.getFodder());
						listFodder=fodderDao.queryList(f, 0, 10);
						if(listFodder==null || listFodder.size()<1){
							log.error("个性化区域规则浏览：个性化规则信息中没有素材！");
							return "默认规则不全，请配置全！";
						}else{
							xml+="<list>\n<billtype>1</billtype>\n";
							xml+="<area>"+areano+"</area>\n<priority>"+rp.getPri()+"</priority>\n";
							docname=listFodder.get(0).getDocname()==null?"":listFodder.get(0).getDocname();
							url=listFodder.get(0).getUrl()==null?"":listFodder.get(0).getUrl();
							xml+="<rescontent>"+docname+"</rescontent>\n<resurl>"+url+"</resurl>\n";
							xml+="</list>\n";
						}
					}
					
				}else{
					//构造当前区域xml
					xml+="<list>\n<billtype>1</billtype>\n";
					xml+="<area>"+areano+"</area>\n<priority>"+rule.getPri()+"</priority>\n";
					xml+="<rescontent>"+docname+"</rescontent>\n<resurl>"+url+"</resurl>\n";
					xml+="</list>\n";
				}
				log.error("个性化区域规则浏览：开始组装xml数据。。。。");
				
					//组织其它区域素材数据
					RuleParam ruleParam=new RuleParam();
					Fodder f=new Fodder();
					List<RuleParam> rList=new ArrayList<RuleParam>();
					List<Fodder> listFodder=new ArrayList<Fodder>();
					for (int i = 0; i < ruleList.size(); i++) {
						if(!ruleList.get(i).getAreaNo().equals(areano)){
							rList=ruleDao.listRuleParamByruluNo(ruleList.get(i));
							if(rList==null || rList.size()<1){
								log.error("个性化区域规则浏览：该区域规则下没有个性化规则信息！");
								return "默认规则不全，请配置全！";
							}else{
								ruleParam=rList.get(0);
								f.setId(ruleParam.getFodder());
								listFodder=fodderDao.queryList(f, 0, 10);
								if(listFodder==null || listFodder.size()<1){
									log.error("个性化区域规则浏览：个性化规则信息中没有素材！");
									return "默认规则不全，请配置全！";
								}else{
									xml+="<list>\n<billtype>1</billtype>\n";
									xml+="<area>"+ruleList.get(i).getAreaNo()+"</area>\n<priority>"+ruleParam.getPri()+"</priority>\n";
									docname=listFodder.get(0).getDocname()==null?"":listFodder.get(0).getDocname();
									url=listFodder.get(0).getUrl()==null?"":listFodder.get(0).getUrl();
									xml+="<rescontent>"+docname+"</rescontent>\n<resurl>"+url+"</resurl>\n";
									xml+="</list>\n";
								}
							}
						}
					}
				
				xml+="</lists>\n</resourcesinfo>\n</checksheet>\n</checksheets>\n</xyk>";
				log.error("个性化区域规则浏览：xml 组装好了！");
				//创建xml
				String xmlName=Config.getValue("product.path").toString()+new Date().getTime()+".xml";
				log.error("个性化区域规则浏览：xml 的名字为 "+xmlName);
				ReadShowFile.createXml(xmlName,xml);
				log.error("个性化区域规则浏览：xml 创建好了！");
				// 纸质
				dataMap.put("wfd", temp.getStorpath());
				//创建xml
				xmlDataMap.put("dif2", xmlName);
				dataMap.put("dif", xmlDataMap);
				dataMap.put("printFlag", 0);
				dataMap.put("templateFlag", "1");
				//获得预纸
				Paper paper=new Paper();
				paper.setPid(paperid);
				List<Paper> pList=paperDao.queryPaperByPaperid(paper);
				
				if(pList==null || pList.size()<1){
					log.debug("个性化区域规则浏览：根据预纸ID没有找到预纸信息！");
					return "没有找到预纸信息";
				}else{
					paper=pList.get(0);
				}
				xmlDataMap = new HashMap<String, Object>();
				List<PaperInfo> listPaperInfo = paperDao.queryPaperInfo(paper.getPid());
				log.debug("个性化区域规则浏览：底板数据大小："+listPaperInfo.size());
				//组装预纸
				int n=1;
				for (int i = 0; i < listPaperInfo.size(); i++) {
					if(listPaperInfo.get(i).getFront()!=null){
						xmlDataMap.put("prePaperPath"+n+"",listPaperInfo.get(i).getFront());
						n++;
					}
				}
				dataMap.put("prePaperPath", xmlDataMap);
				dataMap.put("productionPath",Config.getValue("product.path").toString()+new Date().getTime());
				dataMap.put("e", CommandMaker.OUTPUT_TYPE_PDF);
				dataMap.put("f", Config.getValue("product.path").toString()+new Date().getTime()+".pdf");
				dataMap.put("c", temp.getJobpath());
			}
			
			if(temp.getType().equals("2")){
				String  xml="";
				String docname=fodder.getDocname()==null?"":fodder.getDocname();
				String url=fodder.getUrl()==null?"":fodder.getUrl();
				if(areaType.equals("3") || areaType.equals("4")){
					//查询当前区域下的规则列表
					RuleMaster ru=new RuleMaster();
					ru.setAreaNo(ruleno);
					List<RuleParam> rparamList=ruleDao.listRuleParamByruluNo(ru);
					Fodder f=new Fodder();
					List<Fodder> listFodder=new ArrayList<Fodder>();
					for (RuleParam rp : rparamList) {
						f.setId(rp.getFodder());
						f.setId(rp.getFodder());
						listFodder=fodderDao.queryList(f, 0, 10);
						if(listFodder==null || listFodder.size()<1){
							log.error("个性化区域规则浏览：个性化规则信息中没有素材！");
							return "默认规则不全，请配置全！";
						}else{
							xml+="<list>\n<billtype>2</billtype>\n";
							xml+="<area>"+areano+"</area>\n<priority>"+rp.getPri()+"</priority>\n";
							docname=listFodder.get(0).getDocname()==null?"":listFodder.get(0).getDocname();
							url=listFodder.get(0).getUrl()==null?"":listFodder.get(0).getUrl();
							xml+="<rescontent>"+docname+"</rescontent>\n<resurl>"+url+"</resurl>\n";
							xml+="</list>\n";
						}
					}
					
				}else{
					//构造当前区域xml
					xml+="<list>\n<billtype>2</billtype>\n";
					xml+="<area>"+areano+"</area>\n<priority>"+rule.getPri()+"</priority>\n";
					xml+="<rescontent>"+docname+"</rescontent>\n<resurl>"+url+"</resurl>\n";
					xml+="</list>\n";
				}
				log.error("个性化区域规则浏览：开始组装xml数据。。。。");
			
					//组织其它区域素材数据
					RuleParam ruleParam=new RuleParam();
					Fodder f=new Fodder();
					List<RuleParam> rList=new ArrayList<RuleParam>();
					List<Fodder> listFodder=new ArrayList<Fodder>();
					for (int i = 0; i < ruleList.size(); i++) {
						if(!ruleList.get(i).getAreaNo().equals(areano)){
							rList=ruleDao.listRuleParamByruluNo(ruleList.get(i));
							if(rList==null || rList.size()<1){
								log.error("个性化区域规则浏览：该区域规则下没有个性化规则信息！");
								return "默认个性化规则不全，请配置全！";
							}else{
								ruleParam=rList.get(0);
								f.setId(ruleParam.getFodder());
								listFodder=fodderDao.queryList(f, 0, 10);
								if(listFodder==null || listFodder.size()<1){
									log.error("个性化区域规则浏览：个性化规则信息中没有素材！");
									return "默认规则不全，请配置全！";
								}else{
									xml+="<list>\n<billtype>2</billtype>\n";
									xml+="<area>"+ruleList.get(i).getAreaNo()+"</area>\n<priority>"+ruleParam.getPri()+"</priority>\n";
									docname=listFodder.get(0).getDocname()==null?"":listFodder.get(0).getDocname();
									url=listFodder.get(0).getUrl()==null?"":listFodder.get(0).getUrl();
									xml+="<rescontent>"+docname+"</rescontent>\n<resurl>"+url+"</resurl>\n";
									xml+="</list>\n";
								}
							}
						}
					}
				
				
				xml+="</lists>\n</resourcesinfo>\n</checksheet>\n</checksheets>\n</xyk>";
				log.error("个性化区域规则浏览：xml 组装好了！");
				//创建xml
				String xmlName=Config.getValue("product.path").toString()+new Date().getTime()+".xml";
				log.error("个性化区域规则浏览：xml 文件名 "+xmlName);
				ReadShowFile.createXml(xmlName,xml);
				log.error("个性化区域规则浏览：xml 文件已创建！");
				// html
				dataMap.put("wfd", temp.getStorpath());
				xmlDataMap.put("dif2", xmlName);
				dataMap.put("dif", xmlDataMap);
				dataMap.put("productionPath", Config.getValue("product.path").toString()+new Date().getTime());
				dataMap.put("matterPath", Config.getValue("html.matterPath").toString());
				if(ruleDao.findTsbp("EMAILTITLE")==null){
					return "EmailTitle 没有找到！";
				}
				dataMap.put("EmailTitle", ruleDao.findTsbp("EMAILTITLE").toString());
				dataMap.put("e", CommandMaker.OUTPUT_TYPE_HTML);
				dataMap.put("f", Config.getValue("product.path").toString()+new Date().getTime()+".html");
				dataMap.put("c",  temp.getJobpath());
			}
			
			//告警配置
			dataMap.put("warningconfig", Config.getValue("warningconfig").toString());
			dataList.add(dataMap);
			log.debug("个性化区域规则浏览：NetReader.init()");
			NetReader.init();
			NetServerUtil nsu = new NetServerUtil(dataList);
			NetServerFlowControl control = nsu.start();
			NetServerFlowInterface runnerFlow = null;
			log.debug("个性化区域规则浏览：NetServerFlowSize="+control.getNetServerFlowSize());
			for (int j = 0; j < control.getNetServerFlowSize(); j++) {
				runnerFlow = control.getNetServerFlow(j);
				boolean runSucc = runnerFlow.runSuccess();
				if (!runSucc) {
					if (runnerFlow.lastJobMessage().contains("0030:Nothing to print.")) {
						log.debug("Nothing to print. fileindex flag write is [already pass]");
						return "Nothing to print!";
					}
				}else {
					// 成功，读取pdf文件
					return dataMap.get("f").toString();
				}
			}
		}catch (Exception e) {
			log.error(e);
			return e.getMessage();
		}
		return null;
	}
	
	
}
